// MIT License (MIT)
// 
// Copyright (c) 2014 K Ercan Turkarslan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 

using System;
using System.Net;
using System.Net.Http;

namespace Mios.MiosConnection
{
    public abstract class MiosController : IDisposable
    {
        public String EngineSerial { get; protected set; }
        public String LocalIpAddress { get; protected set; }

        public String Username { get; protected set; }
        public String Password { get; protected set; }

        public HttpClient Connection { get; protected set; }

        #region Constructor(s)

        protected MiosController(String engineSerial, String localIpAddress, String username, String password)
        {
            Connection = null;

            EngineSerial = engineSerial;
            LocalIpAddress = localIpAddress;

            Username = username;
            Password = password;
        }

        #endregion

        #region IDisposable method

        public void Dispose()
        {
            CloseConnection();
        }

        #endregion

        #region Connection methods

        public abstract Boolean IsConnectionStale();

        public Boolean IsConnected()
        {
            return (Connection != null);
        }

        public virtual Boolean CanConnectLocally()
        {
            return !String.IsNullOrEmpty(LocalIpAddress);            
        }

        public virtual Boolean EstablishLocalConnection()
        {
            if (IsConnected())
                CloseConnection();

            return CanConnectLocally();
        }

        public abstract Boolean EstablishRemoteConnection(Boolean useSecondaryServer = false);

        public void CloseConnection()
        {
            if (Connection == null)
                return;

            Connection.Dispose();
            Connection = null;            
        }

        #endregion

        // Vera does not have a consistent behavior for error. The error reporting 
        // behavior may even change depending on whether http call is local or remote.
        //
        // This method needs to be updated/rewritten overtime for various error conditions.
        public virtual String GetString(String httpString)
        {
            try
            {
                var httpTask = Connection.GetStringAsync(String.Format("data_request?{0}", httpString));

                httpTask.Wait();

                if (httpTask.IsCanceled)
                    throw new MiosConnectionException("HttpGetString canceled!", httpTask.Exception);

                if (httpTask.IsFaulted)
                    throw new MiosConnectionException("HttpGetString failed!", httpTask.Exception);

                if (httpTask.Result.StartsWith("error:"))
                    throw new MiosConnectionException(httpTask.Result);

                return httpTask.Result;
            }
            catch (AggregateException ex)
            {
                throw new MiosConnectionException("HttpGetString failed!", ex);
            }
            catch (WebException ex)
            {
                throw new MiosConnectionException("HttpGetString failed!", ex);
            }
        }
    }
}